var local;
var map;
var key = getCookie("key");
var ifcart = getQueryString("ifcart");
var goods_id = getQueryString("goods_id");
var pintuangroup_id = getQueryString("pintuangroup_id");
var pintuan_id = getQueryString("pintuan_id");
var common_goods_voucher = null;
var store_address_info = null;
var address_type = 1;
var time_goods_voucher = null;

if(getCookie('inviter_id')){
    var member_id = getCookie('inviter_id');
}else{
    var member_id = getQueryString('inviter_id');
}
console.log(getCookie('inviter_id'));
var inviter_id = member_id;
var _init = null;
var member_type = getUserType()? getUserType(): 3;

if (ifcart == 1) {
    var cart_id = getQueryString("cart_id")     // 1:3
} else {
    var cart_id = goods_id + "|" + getQueryString("buynum")
}

var pay_name = "online";
var invoice_id = 0;
var address_id, vat_hash, offpay_hash, offpay_hash_batch, voucher, pd_pay, password, fcode = "",
    rcb_pay, payment_code;
var message = {};
var freight_hash, city_id, area_id;
var area_info;
var trade_mode = 0;
$(function() {
    // $.ajax({
    //     url: ApiUrl + "/Index/get_baidu_ak.html",
    //     async:false,
    //     dataType: "json",
    //     success: function(e) {
    //         loadScript("https://api.map.baidu.com/getscript?v=2.0&ak="+e.result.baidu_ak+"&services=&t=",function(){
    //             init_map();
    //         });
    //     }
    // })


	// 门店自提
	function setAddressType(t) {
		address_type = t;
		$('.address-type').removeClass('active');
		$('.address-type-' + t).addClass('active');
	}


	// 粘贴自动识别
	$('body').on('paste', '.clip-content', function () {
		var thisObj = $(this);
		setTimeout(function () {
			var content = thisObj.val();
			addressSmartParse(content, function (res) {
				$('#true_name, #real_name').val(res.name || '');
				$('#mob_phone').val(res.mobile || '');
				$('#area_info').val(res.address_detail.area_info).attr('data-areaid', res.address_detail[3].area_id || 0).attr('data-areaid2', res.address_detail[2].area_id || 0);
				$('#id_card_no').val(res.idno);
				$('#address').val(res.address_detail.street || '');
			});
		}, 100);
	});

    $(document).on('tap','#returnOK',function () {
        layer.open({
            content: '优惠不等人，再考虑一下呗'
            ,btn: ['继续购买','去意已决']
            ,yes: function(index){
                layer.close(index);
            },no:function () {
                mui.back();
            }
        });
    });

    $(document).on('tap','#returnClose',function () {
        layer.open({
            content:"跳过支付时效后，订单会被取消哦, 确认放弃付款吗？"
            ,btn: ['继续支付','确定离开']
            ,yes: function(index){
		        pageChange('../member/order_detail.html', {
			        pay_sn: window.current_pay_sn
		        })
            },no:function () {
		        mui.back();
            }
        });
    });

    $("#list-address-valve").on('tap',function() {
        $.ajax({
            type: "post",
            url: ApiUrl + "/Memberaddress/address_list.html",
            data: {
                key: key
            },
            dataType: "json",
            async: false,
            success: function(e) {
                if (e.result.address_list == null) {
                    return false
                }

                // 记录地址
                window.address_list = e.result.address_list;

                var a = e.result;
                a.address_id = address_id;
                a.trade_mode = trade_mode;
                var i = template("list-address-add-list-script", a);
                $("#list-address-add-list-ul").html(i)
            }
        })
    });
    $.animationLeft({
        valve: "#list-address-valve",
        wrapper: "#list-address-wrapper",
        scroll: "#list-address-scroll"
    });
    $("#list-address-add-list-ul").on("tap", "li dl",
        function() {
    	    var rowObj = $(this).parents('li');
	        rowObj.addClass("selected").siblings().removeClass("selected");
            eval("address_info = " + rowObj.attr("data-param"));
            _init(address_info.address_id);
            $("#list-address-wrapper").find(".header-l > a").click()
        });

    // 地址编辑
	$('body').on('tap', '.edit-address', function () {
		var index = $(this).data('index');
		var address_detail = window.address_list[index];
		console.log(address_detail);
		addressSet(address_detail);
	});

	function addressSet(address_detail) {
		if(address_detail.address_id) {
			$('#new-address-wrapper .header-title h1').html('编辑收货地址');
		} else {
			$('#new-address-wrapper .header-title h1').html('新增收货地址');
		}

		$('#new-address-wrapper').removeClass("hide").removeClass("right").addClass("left");
		$('#address_id').val(address_detail.address_id || '');
		$('#true_name').val(address_detail.address_realname || '');
		$('#real_name').val(address_detail.real_name || '');
		$('#mob_phone').val(address_detail.address_mob_phone || '');
		$('#area_info').val(address_detail.area_info).attr('data-areaid', address_detail.area_id || 0).attr('data-areaid2', address_detail.city_id || 0);
		$('#address').val(address_detail.address_detail || '');
		$('#id_card_no').val(address_detail.id_card_no || '');
		$('#img_1').val(address_detail.id_card_front || '');
		$('#img_2').val(address_detail.id_card_back || '');
	}

	$.animationLeft({
		valve: "#new-address-valve",
		wrapper: "#new-address-wrapper",
		scroll: ""
	});
	$.animationLeft({
		valve: "#new-address-valve-2",
		wrapper: "#new-address-wrapper-2",
		scroll: ""
	});
    $.animationLeft({
        valve: "#select-payment-valve",
        wrapper: "#select-payment-wrapper",
        scroll: ""
    });
    $("#new-address-wrapper").on("tap", "#area_info",
        function() {
            $.areaSelected({
                success: function(e) {
                    city_id = e.area_id_2 == 0 ? e.area_id_1: e.area_id_2;
                    area_id = e.area_id;
                    area_info = e.area_info;
                    $("#area_info").val(e.area_info).attr('data-areaid', area_id).attr('data-areaid2', city_id);
                    change_map(e.area_info);
                }
            });
        });
    $(".public-pos").on("tap", function() {
        $.addressSelected({success: function(a) {
                $('#latitude').val(a.lat);
                $('#longitude').val(a.lng);
                $('#address').val(a.address);
            }})
    })
    $.animationLeft({
        valve: "#invoice-valve",
        wrapper: "#invoice-wrapper",
        scroll: ""
    });
    template.helper("isEmpty",
        function(t) {
            return $.isEmpty(t);
        });
    template.helper("pf",
        function(e) {
            return parseFloat(e) || 0
        });
    template.helper("p2f",
        function(e) {
            return (parseFloat(e) || 0).toFixed(2)
        });
    _init = function(address_id) {
        baseApi.post("Memberbuy/buy_step1", {
            cart_id: cart_id,
            ifcart: ifcart,
	        address_id: address_id
        }, function(re, e) {
            if(member_id){
                $('#select-payment-valve').parent().hide();
                $('#invoice-valve').parent().hide();
            }
	        var result = e.result.cart_list.goods_list;
	        trade_mode = e.result.trade_mode; // 记录贸易类型

            // 可以小区门店收货
	        if(re.store_receive_address_info) {
		        store_address_info = re.store_receive_address_info;
	        	var store_receive = $('.store-receive-wrap').removeClass('mui-hidden');
		        $('.store-receive-address').text(re.store_receive_address_info.area_info + ' ' + re.store_receive_address_info.address_detail);
		        store_receive.find('.store_receive_username').text(re.store_receive_address_info.address_realname || '');
		        store_receive.find('.store_receive_mobile').text(re.store_receive_address_info.address_mob_phone || '');

		        $('#store_receive_true_name').val(re.store_receive_address_info.address_realname || '');
		        $('#store_receive_mob_phone').val(re.store_receive_address_info.address_mob_phone || '');

		        if(re.address_info && re.address_info.address_id == store_address_info.address_id) {
			        // 门店自提
			        setAddressType(2);
		        } else {
			        setAddressType(1);
		        }
	        }

            var arr = Object.keys(e.result.cart_list.goods_list);
            checkLogin(e.login);

            if (e.code != 10000) {
                layer.open({content: e.message, btn: '我知道了'});
                return false
            }

            changeTradeMode();

            for (var n in result) {
                if( trade_mode >= 1 && trade_mode <= 2){
                   $('.real-name-filed').removeClass('mui-hidden');
                   break;
                }
            }

            e.result.WapSiteUrl = WapSiteUrl;
            e.result.member_type = member_type;
            var i = template("goods_list", e.result);
            $("#deposit").html(i);

            // APP内显示的内容
            if(isPlusReady()) {
            	$('.app-show').removeClass('mui-hidden');
                // APP内显示仓库
                $('.transport-title').show();
                //APP显示优惠券
                $('.sctouch-cart-block').show();
            }
            if (fcode == "") {
                var a = e.result.cart_list.goods_list.is_goodsfcode;
                if (a == "1") {
                    $("#container-fcode").removeClass("hide");
                    goods_id = e.result.cart_list[t].goods_list[0].goods_id
                }
            }
            $("#container-fcode").find(".submit").on('tap',function() {
                fcode = $("#fcode").val();
                if (fcode == "") {
                    layer.open({content: '请填写F码',skin: 'msg',time: 2});
                    return false
                }
                $.ajax({
                    type: "post",
                    url: ApiUrl + "/Memberbuy/check_fcode.html",
                    dataType: "json",
                    data: {
                        key: key,
                        goods_id: goods_id,
                        fcode: fcode
                    },
                    success: function(e) {
                        if (e.code != 10000) {
                            layer.open({content: e.message,skin: 'msg',time: 2});
                            return false
                        }
                        layer.open({content: '验证成功',skin: 'msg',time: 2});
                        $("#container-fcode").addClass("hide")
                    }
                })
            });

            if ($.isEmptyObject(e.result.address_info)) {
                layer.open({
                    content: '请添加地址？'
                    , btn: ['确认', '取消']
                    , yes: function (index) {
                        layer.close(index);
                        addressSet({});
                    }
                    , no: function (index) {
                        layer.close(index);
                    }
                });
                return false
            }
            if (typeof e.result.inv_info.invoice_id != "undefined") {
                invoice_id = e.result.inv_info.invoice_id
            }
            $("#invContent").html(e.result.inv_info.content);
            vat_hash = e.result.vat_hash;
            freight_hash = e.result.freight_hash;
            insertHtmlAddress(e.result.address_info, e.result.address_api);
            voucher = "";
            voucher_temp = [];
            voucher_temp.push([e.result.cart_list.voucher_info.vouchertemplate_id + "|" + e.result.cart_list.voucher_info.voucher_price])
            voucher = voucher_temp.join(",");
            $("#Total").html(e.result.final_total);
            var a = 0;
            a += parseFloat(e.result.final_total);
            if(typeof e.result.cart_list.voucher_info.length > 0){
                a -= e.result.cart_list.voucher_info.voucher_price;
            }
            //console.log(e.result.cart_list.goods_list);
            message = "";
            $("#Message" ).on("change",
                function() {
                    message = $(this).val()
                })
            var r = a;
            if (r <= 0) {
                r = 0
            }
            var arr = Object.keys(e.result.cart_list.goods_list);
            if(arr.length > 1){
                $("#totalPrice,#onlineTotal").html(r.toFixed(2)+ '<sapn>'+ '(已含税)'+'</sapn>');
            }else{
                $("#totalPrice,#onlineTotal").html(r.toFixed(2));
            }

            window.final_order_amount = r;
            // 可用优惠券数量加载
            // voucherNumLoad();
	        // 更新优惠券显示
	        updateOrderVoucher();
        })
    };

    // 优惠券数量加载
    function voucherNumLoad() {
	    // 选择优惠券加载
	    $('.select-voucher').each(function () {
		    var thisObj = $(this);
		    var time_goods_id = $(this).data('time_goods_id');
		    baseApi.get("/Membervoucher/voucher_num.html", {
			    order_amount: window.final_order_amount,
			    time_goods_id: time_goods_id
		    }, function (result) {
			    thisObj.find('.voucher-num').text(result);
		    });
	    });

	    $.animationLeft({
		    valve: ".select-voucher",
		    wrapper: "#list-voucher-wrapper",
		    // scroll: "#list-voucher-scroll",
		    scroll: ""
	    });
    }

    // 优惠券选择
    $('body').on('tap', '.select-voucher', function () {
        var time_goods_id = $(this).data('time_goods_id');

        window.voucher_choose_type = 'common';

        baseApi.get("/Membervoucher/voucher_list.html", {
            order_amount: window.final_order_amount,
	        time_goods_id: time_goods_id,
	        search_type: 'common'
        }, function(result) {
            var i = template("voucher-list-script", result);
            console.log(result);
            $("#voucher-list").html(i);
        })
    });

    //      data-voucher_id="<%=v.voucher_id%>"
	//       data-vouchertemplate_is_common="<%=v.vouchertemplate_is_common%>"
	//       data-vouchertemplate_allow_superposition="<%=v.vouchertemplate_allow_superposition%>"
	//       data-voucher_price="<%=v.voucher_price%>">
    // 选择优惠券
    $('body').on('tap', '.voucher-choose', function () {
	    var voucher_id = $(this).data('voucher_id');
	    var vouchertemplate_id = $(this).data('vouchertemplate_id');
	    var vouchertemplate_is_common = $(this).data('vouchertemplate_is_common');
	    var vouchertemplate_allow_superposition = $(this).data('vouchertemplate_allow_superposition');
	    var voucher_price = $(this).data('voucher_price');
	    var time_goods_id = $(this).data('time_goods_id');

	    if(window.voucher_choose_type === 'time_goods') {
		    if(!voucher_id) {
                time_goods_voucher = null;
		    } else {
		        if(common_goods_voucher && (common_goods_voucher.vouchertemplate_allow_superposition == 0 || vouchertemplate_allow_superposition == 0)) {
		            mui.toast('选定优惠券不可叠加使用');
		            return;
                }
			    time_goods_voucher = {
				    voucher_id: voucher_id,
				    vouchertemplate_id: vouchertemplate_id,
				    goods_id: goods_id,
				    vouchertemplate_is_common: vouchertemplate_is_common,
				    vouchertemplate_allow_superposition: vouchertemplate_allow_superposition,
				    voucher_price: voucher_price
                };
            }
        } else {
		    if(!voucher_id) {
			    common_goods_voucher = null;
		    } else {
			    if(time_goods_voucher && (time_goods_voucher.vouchertemplate_allow_superposition == 0 || vouchertemplate_allow_superposition == 0)) {
				    mui.toast('选定优惠券不可叠加使用');
				    return;
			    }
			    common_goods_voucher = {
				    voucher_id: voucher_id,
				    vouchertemplate_id: vouchertemplate_id,
				    vouchertemplate_is_common: vouchertemplate_is_common,
				    vouchertemplate_allow_superposition: vouchertemplate_allow_superposition,
				    voucher_price: voucher_price
			    };
		    }
        }
	    // 更新优惠券显示
	    updateOrderVoucher();

	    $("#list-voucher-wrapper").find(".header-l > a").click();
    });

    // 更新优惠券显示
    function updateOrderVoucher() {
	    voucher = "";
	    var voucher_temp = [];
        var order_amount = window.final_order_amount;
	    $('.buy-item .select-voucher')
		    .find('.voucher-desc').text('未选择');
	    if(time_goods_voucher) {
		    $('.select-voucher[data-time_goods_id="'+time_goods_voucher.time_goods_id+'"]')
			    .find('.voucher-desc').text(time_goods_voucher.voucher_price + ' 元');
		    order_amount -= time_goods_voucher.voucher_price;
		    voucher_temp.push([time_goods_voucher.vouchertemplate_id + "|" + time_goods_voucher.voucher_price])
	    }

	    if(common_goods_voucher) {
		    $('.select-voucher[data-time_goods_id="0"]')
			    .find('.voucher-desc').text(common_goods_voucher.voucher_price + ' 元');
		    order_amount -= common_goods_voucher.voucher_price;
		    voucher_temp.push([common_goods_voucher.vouchertemplate_id + "|" + common_goods_voucher.voucher_price])
	    } else {
		    $('.select-voucher[data-time_goods_id="0"]')
			    .find('.voucher-desc').text('未选择');
	    }

	    voucher = voucher_temp.join(",");

	    $("#totalPrice,#onlineTotal").html(order_amount.toFixed(2));
    }

    rcb_pay = 0;
    pd_pay = 0;
    _init();
    var insertHtmlAddress = function(e, a) {
    	if(!e) return;
        address_id = e.address_id;
        if(address_type == 2) {
	        $("#vtrue_name").html('快递到家');
	        $("#vmob_phone").html('');
	        $("#vaddress").html('请选择收件地址');
        } else {
	        $("#vtrue_name").html(e.address_realname);
	        $("#vmob_phone").html(e.address_mob_phone);
	        $("#vaddress").html(e.area_info + e.address_detail);
        }
        area_id = e.area_id;
        city_id = e.city_id;
        if (a.content) {
            for (var i in a.content) {
                $("#storeFreight" + i).html(parseFloat(a.content[i]).toFixed(2))
            }
        }
        offpay_hash = a.offpay_hash;
        offpay_hash_batch = a.offpay_hash_batch;
        if (a.allow_offpay == 1) {
            $("#payment-offline").show()
        }
        if (!$.isEmptyObject(a.no_send_tpl_ids)) {
            $("#ToBuyStep2").parent().removeClass("ok");
            for (var t = 0; t < a.no_send_tpl_ids.length; t++) {
                $(".transportId" + a.no_send_tpl_ids[t]).show()
            }
        } else {
            $("#ToBuyStep2").parent().addClass("ok")
        }
    };
    $("#payment-online").on('tap',function() {
        pay_name = "online";
        $("#select-payment-wrapper").find(".header-l > a").click();
        $("#select-payment-valve").find(".current-con").html("在线支付");
        $(this).addClass("sel").siblings().removeClass("sel")
    });
    $("#payment-offline").on('tap',function() {
        pay_name = "offline";
        $("#select-payment-wrapper").find(".header-l > a").click();
        $("#select-payment-valve").find(".current-con").html("货到付款");
        $(this).addClass("sel").siblings().removeClass("sel")
    });
    $.sValid.init({
        rules: {
            true_name: "required",
            mob_phone: "required",
        },
        messages: {
            true_name: "姓名必填！",
            mob_phone: "手机号必填！",
        },
        callback: function(e, a, i) {
            if (e.length > 0) {
                var t = "";
                $.map(a,
                    function(e, a) {
                        t += "<p>" + e + "</p>"
                    });
                layer.open({content: t, skin: 'msg', time: 2});
            }
        }
    });

	$("#add_address_form").find(".btn").on('tap',function() {
		if ($.sValid()) {
			var e = {};
			e.key = key;
			e.trade_mode = trade_mode;
			e.inviter_id = inviter_id;
			e.address_id = $("#address_id").val();
			e.true_name = $("#true_name").val();
			e.mob_phone = $("#mob_phone").val();
			e.address = $("#address").val();
			e.real_name = $("#real_name").val();
			e.id_card_no = $('#id_card_no').val();
			e.longitude = $("#longitude").val();
			e.latitude = $("#latitude").val();
			e.city_id = $("#area_info").attr("data-areaid2");
			e.area_id = $("#area_info").attr("data-areaid");
			e.area_info = $("#area_info").val();
			e.id_card_front = $(".img_1").val();
			e.id_card_back = $(".img_2").val();
			e.is_default = 0;
			e.store_receive = 0;

			$.ajax({
				type: "post",
				url: ApiUrl + "/Memberaddress/address_add.html",
				data: e,
				dataType: "json",
				success: function(a) {
					if(a.code != 10000){
						layer.open({content: a.message, skin: 'msg', time: 2});
						return false;
					}
					if (a.code == 10000) {
						e.address_id = a.result.address_id;
						_init(e.address_id);
						$("#new-address-wrapper,#list-address-wrapper").find(".header-l > a").click()
					}
				}
			})
		}
	});

	// 自提保存
	$("#add_address_form-2").find(".btn").on('tap',function() {

		var e = {};
		e.key = key;
		e.address_id = store_address_info.address_id || 0;
		e.trade_mode = trade_mode;
		e.inviter_id = inviter_id;
		e.true_name = $("#store_receive_true_name").val().trim();
		e.mob_phone = $("#store_receive_mob_phone").val().trim();
		e.is_default = 0;
		e.store_receive = 1;

		if(!e.true_name) {
			mui.toast('请输入收件人名');
			return;
		}
		if(!e.mob_phone) {
			mui.toast('请输入联系电话');
			return;
		}

		$.ajax({
			type: "post",
			url: ApiUrl + "/Memberaddress/address_add.html",
			data: e,
			dataType: "json",
			success: function(a) {
				if(a.code != 10000){
					layer.open({content: a.message, skin: 'msg', time: 2});
					return false;
				}
				if (a.code == 10000) {
					e.address_id = a.result.address_id;
					_init(e.address_id);
					$("#new-address-wrapper-2").find(".header-l > a").click()
				}
			}
		})
	});

    $('input[name="id_card"]').ajaxUploadImage({
        url: ApiUrl + "/Memberaddress/upload_pic.html",
        data: {
            key: key
        },
        start: function(e) {
            e.parent().after('<div class="upload-loading"><i></i></div>');
            e.parent().siblings(".pic-thumb").remove()
        },
        success: function(a, e) {

            checkLogin(e.login);
            if (e.code != 10000) {
                a.parent().siblings(".upload-loading").remove();
                layer.open({content: '图片尺寸过大！',skin: 'msg',time: 2});
                return false
            }
            a.parent().after('<div class="pic-thumb"><img src="' + e.result.pic + '"/></div>');
            a.parent().siblings(".upload-loading").remove();
            a.parents("a").next().val(e.result.pic);
        }
    });

    $("#invoice-noneed").on('tap',function() {
        $(this).addClass("sel").siblings().removeClass("sel");
        $("#invoice_add,#invoice-list").hide();
        invoice_id = 0
    });
    $("#invoice-need").on('tap',function() {
        $(this).addClass("sel").siblings().removeClass("sel");
        $("#invoice-list").show();
        $.ajax({
            type: "post",
            url: ApiUrl + "/Memberinvoice/invoice_content_list.html",
            data: {
                key: key
            },
            dataType: "json",
            success: function(e) {
                checkLogin(e.login);
                var a = e.result;
                var i = "";
                $.each(a.invoice_content_list,
                    function(e, a) {
                        i += '<option value="' + a + '">' + a + "</option>"
                    });
                $("#inc_content").append(i)
            }
        });
        $.ajax({
            type: "post",
            url: ApiUrl + "/Memberinvoice/invoice_list.html",
            data: {
                key: key
            },
            dataType: "json",
            success: function(e) {
                checkLogin(e.login);
                var a = template("invoice-list-script", e.result);
                $("#invoice-list").html(a);
                if (e.result.invoice_list.length > 0) {
                    invoice_id = e.result.invoice_list[0].invoice_id
                }
                $(".del-invoice").on('tap',function() {
                    var e = $(this);
                    var a = $(this).attr("invoice_id");
                    $.ajax({
                        type: "post",
                        url: ApiUrl + "/Memberinvoice/invoice_del.html",
                        data: {
                            key: key,
                            invoice_id: a
                        },
                        success: function(a) {
                            if (a) {
                                e.parents("label").remove()
                            }
                            return false
                        }
                    })
                })
            }
        })
    });
    $('input[name="invoice_title_select"]').on('tap',function() {
        if ($(this).val() == "person") {
            $("#inv-title-li").hide();
            $("#inv-code-li").hide();
        } else {
            $("#inv-title-li").show();
            $("#inv-code-li").show();
        }
    });
    $("#invoice-div").on("tap", "#invoiceNew",
        function() {
            invoice_id = 0;
            $("#invoice_add,#invoice-list").show()
        });
    $("#invoice-list").on("tap", "label",
        function() {
            invoice_id = $(this).find("input").val()
        });
    $("#invoice-div").find(".btn-l").on('tap',function() {
        if ($("#invoice-need").hasClass("sel")) {
            if (invoice_id == 0) {
                var e = {};
                e.key = key;
                e.invoice_title_select = $('input[name="invoice_title_select"]:checked').val();
                e.invoice_title = $("input[name=invoice_title]").val();
                e.invoice_code = $("input[name=invoice_code]").val();
                e.invoice_content = $("select[name=invoice_content]").val();
                $.ajax({
                    type: "post",
                    url: ApiUrl + "/Memberinvoice/invoice_add.html",
                    data: e,
                    dataType: "json",
                    success: function(e) {
                        if (e.result.invoice_id > 0) {
                            invoice_id = e.result.invoice_id
                        }
                    }
                });
                $("#invContent").html(e.invoice_title + " " + e.invoice_code + " " + e.invoice_content)
            } else {
                $("#invContent").html($("#inv_" + invoice_id).html())
            }
        } else {
            $("#invContent").html("不需要发票")
        }
        $("#invoice-wrapper").find(".header-l > a").click()
    });
    $("#ToBuyStep2").click(function() {
        var message = $('#Message').val();

        // 显示加载中
        window.layerIndex = layer.open({
            type: 2,
	        shadeClose: false
        });
        $.ajax({
            type: "post",
            url: ApiUrl + "/Memberbuy/buy_step2.html",
            data: {
                key: key,
                ifcart: ifcart,
                inviter_id: inviter_id,
                cart_id: cart_id,
                address_id: address_id,
                vat_hash: vat_hash,
                offpay_hash: offpay_hash,
                offpay_hash_batch: offpay_hash_batch,
                pay_name: pay_name,
                invoice_id: invoice_id,
                // voucher: voucher,
                voucher: 'undefined|undefined',
                pd_pay: pd_pay,
                password: password,
                fcode: fcode,
                rcb_pay: rcb_pay,
                pay_message: message,
                pintuangroup_id: pintuangroup_id,
                pintuan_id: pintuan_id,
				trade_mode: trade_mode
            },
            dataType: "json",
            success: function(e) {
                layer.close(window.layerIndex);
                checkLogin(e.login);

                if (e.code != 10000) {
                    layer.open({content: e.message,skin: 'msg',time: 2});
                    return false
                }

                if(e.result.length >1){
                    layer.open({
                        content: '订单创建成功，请到订单中心去支付！'
                        , btn: ['确定']
                        , yes: function (index) {
                                pageChange("../member/order_list.html")
                        }
                    });
                }else{
                    delCookie("cart_count");
                    for(var index in e.result) {
                        window.current_pay_sn = e.result[index].pay_sn; // 当前支付单号
                        toPay(e.result[index].pay_sn, "memberbuy", "pay");
                    }
                }
            }
        })
    })
});

function init_map(){
    map = new BMap.Map('mymap');
    var lng=$('#longitude').val();
    var lat=$('#latitude').val();
    if(lng=='' && lat==''){
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function (r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                var lng = r.point.lng;
                var lat = r.point.lat;
                var point = new BMap.Point(lng, lat);
                map.centerAndZoom(point, 16);
                document.getElementById("longitude").value = lng;
                document.getElementById("latitude").value = lat;

            } else {
                alert('failed' + this.getStatus());
            }
        }, {enableHighAccuracy: true})
    }else{
        var point = new BMap.Point(lng, lat);
        map.centerAndZoom(point, 16);
    }
    var options = {
        onSearchComplete: function (results) {
            // 判断状态是否正确
            if (local.getStatus() == BMAP_STATUS_SUCCESS) {
                if (results.getCurrentNumPois() > 0) {
                    document.getElementById("longitude").value = results.getPoi(0).point.lng;
                    document.getElementById("latitude").value = results.getPoi(0).point.lat;
                    setCookie('longitude', results.getPoi(0).point.lng, 30);
                    setCookie('latitude', results.getPoi(0).point.lat, 30);
                }
            }
        }
    };
    local = new BMap.LocalSearch(map, options);
}
function change_map(name){
    if(name!=''){
        /*---- 暂时禁用地图定位 ----- */
        // map.centerAndZoom(name,16);
        // map.setCurrentCity(name);
        // local.search(name);
//        var point=map.getCenter();
//        document.getElementById("longitude").value = point.lng;
//        document.getElementById("latitude").value = point.lat;
    }

}
// 页面数据重新加载(直接跳转到订单列表)
window.pageReload = function () {

    // 关闭弹出层()
    $('.sctouch-bottom-mask-close').click();
    if(window.pageReloadTimes) {
        // 第二次返回，关闭当前页
        closeCurrentWindow();
        return;
    }

    if(!window.current_pay_sn) {
        _init();
    } else {
	    window.pageReloadTimes = window.pageReloadTimes || 1;
        // APP 支付返回直接跳转到订单详情
        pageChange('../member/order_detail.html', {
            pay_sn: window.current_pay_sn
        });
    }
}